package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.builder.FullOrderDataBuilder;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.exception.CustomException;
import com.itheima.reggie.mapper.OrdersMapper;
import com.itheima.reggie.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.yaml.snakeyaml.events.Event;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
@Transactional
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;


    @Override
    public void submit( Orders orders) {
        /*
            提交订单：
                0.先把当前购物车信息查询出来，然后封装到订单明细中
                1.先封装订单明细->订单->清除购物车->提交到新的页面
         */
        //固定ordersid
        orders.setId(IdWorker.getId());
        FullOrderDataBuilder fullOrderDataBuilder = new FullOrderDataBuilder(shoppingCartService,orderDetailService,userService,addressBookService,orders);
        FullOrderData fullOrderData = fullOrderDataBuilder.builderOrderDetail().builderOrder().builder();
        Orders ordersInfo = fullOrderData.getOrders();
        List<OrderDetail> orderDetailInfo = fullOrderData.getOrderDetailList();

        this.save(ordersInfo);
        orderDetailService.saveBatch(orderDetailInfo);

        /*
        清空购物车
         */
        LambdaQueryWrapper<ShoppingCart> cartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        cartLambdaQueryWrapper.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
        shoppingCartService.remove(cartLambdaQueryWrapper);
//        LambdaQueryWrapper<ShoppingCart> cartlqw = new LambdaQueryWrapper<>();
//        cartlqw.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
//
//        List<ShoppingCart> shoppingCarts = shoppingCartService.list(cartlqw);

//        if (shoppingCarts==null && shoppingCarts.size()==0){
//            throw new CustomException("当前购物车为空，不能下单");
//        }

        //雪花生成器
//        long orderId = IdWorker.getId();//订单号
        //这个地方可能会有高并发，高并发场景下，需要确保数据安全，所以他就用了这个原子类
//        AtomicInteger amount = new AtomicInteger(0);
        //int amount=0,其实它这里是是局部变量，随着方法压栈，并在方法区中，不存在什么高并发，但是为了和课程保持一致12。

        /*
        订单明细表
         */
//        List<OrderDetail> orderDetailList = shoppingCarts.stream().map((cart) -> {
//            OrderDetail orderDetail = new OrderDetail();
//            orderDetail.setName(cart.getName());
//            orderDetail.setImage(cart.getImage());
//            orderDetail.setOrderId(orderId);
//            orderDetail.setDishId(cart.getDishId());
//            orderDetail.setSetmealId(cart.getSetmealId());
//            orderDetail.setDishFlavor(cart.getDishFlavor());
//            orderDetail.setNumber(cart.getNumber());
//            orderDetail.setAmount(cart.getAmount());
//            //amount+=单价*数量
//            amount.addAndGet(cart.getAmount().multiply(new BigDecimal(cart.getNumber())).intValue());//总价,就是累加
//            return orderDetail;
//        }).collect(Collectors.toList());
//        orderDetailService.saveBatch(orderDetailList);



        /*
            订单表
         */
//        LambdaQueryWrapper<AddressBook> addresslqw = new LambdaQueryWrapper<>();
//        addresslqw.eq(AddressBook::getId, orders.getAddressBookId());
//        AddressBook addressBook = addressBookService.getOne(addresslqw);
//        if (addressBook==null){
//            throw new CustomException("用户地址信息有误，不能下单");
//        }
//        orders.setId(orderId);
//        orders.setNumber(String.valueOf(orderId));
//        orders.setStatus(2);
//        orders.setUserId(BaseContext.getCurrentId());
//        orders.setOrderTime(LocalDateTime.now());
//        orders.setAmount(new BigDecimal(amount.get()));
//        orders.setCheckoutTime(LocalDateTime.now());
//
//        User user = userService.getById(BaseContext.getCurrentId());
//
//        orders.setUserName(user.getName());
//        orders.setPhone(addressBook.getPhone());
//        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
//                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
//                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
//                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
//        orders.setConsignee(addressBook.getConsignee());

//        this.save(orders);

//        shoppingCartService.remove(cartlqw);//清空购物车
//        LambdaQueryWrapper<User> userlqw = new LambdaQueryWrapper<>();
//        userlqw.eq(User::getId, BaseContext.getCurrentId());
//        User user = userService.getOne(userlqw);
    }
}
